package com.baidu.health.filter;

import com.alibaba.fastjson.JSON;
import com.baidu.health.mapper.TbArticleMapper;
import com.baidu.health.mapper.TbDocumentMapper;
import com.baidu.health.pojo.TbArticle;
import com.baidu.health.pojo.TbDocument;
import com.baidu.health.pojo.TbSensitivity;
import com.baidu.health.pojo.resultVo.articleVo;
import com.baidu.health.service.TbArticleServiceImpl;
import com.baidu.health.utils.KeyWordFilter;
import com.rabbitmq.client.Channel;
import org.elasticsearch.action.search.SearchRequest;
import org.elasticsearch.client.RequestOptions;
import org.elasticsearch.client.RestHighLevelClient;
import org.elasticsearch.index.query.QueryBuilders;
import org.elasticsearch.search.SearchHit;
import org.elasticsearch.search.builder.SearchSourceBuilder;
import org.springframework.amqp.core.Message;
import org.springframework.amqp.rabbit.annotation.RabbitListener;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.web.bind.annotation.RequestBody;

import java.util.ArrayList;
import java.util.Date;
import java.util.Iterator;
import java.util.List;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

@Component
public class articleFilter {

    @Autowired
    TbArticleServiceImpl articleService;

    @Autowired
    TbArticleMapper articleMapper;

    @Autowired
    TbDocumentMapper documentMapper;

    @Autowired
    RestHighLevelClient restHighLevelClient;

    @RabbitListener(queues = "article",concurrency = "1")
    public void articleFilters(@RequestBody TbArticle article, Message message , Channel channel) throws Exception{

//        KeyWordFilter keyWordFilter = new KeyWordFilter();

        boolean checkTitle = this.doFilter(article.getArticleTitle());
        boolean checkContent = this.doFilter(article.getArticleContent());

        if ( checkTitle && checkContent ){
            if ( article.getArticleFile() != null ){
                TbDocument document = new TbDocument();
                document.setArticleId(article.getArticleId());
                document.setArticleTitle(article.getArticleTitle());
                document.setDocumentSrc(article.getArticleFile());
                documentMapper.insert(document);
            }
            long deliveryTag = message.getMessageProperties().getDeliveryTag();
            channel.basicAck(deliveryTag,false);
            channel.basicNack(deliveryTag,false,false);
        }else {
            article.setUpdateTime(new Date());
            article.setCheckFlag(2);
            articleMapper.updateById(article);
            articleService.sync();
            long deliveryTag = message.getMessageProperties().getDeliveryTag();
            channel.basicAck(deliveryTag,false);
            channel.basicNack(deliveryTag,false,false);
        }

    }


    private static Pattern pattern = null;
    private static int keywordsCount = 0;

    public boolean doFilter(String str) throws Exception{
        // 从words.properties初始化正则表达式字符串
        StringBuffer patternBuffer = new StringBuffer();

		SearchRequest request = new SearchRequest("min");
		SearchSourceBuilder builder = new SearchSourceBuilder();
		builder.query(QueryBuilders.matchAllQuery());
		builder.size(5000);
		request.source(builder);
		SearchHit[] hits = restHighLevelClient.search(request, RequestOptions.DEFAULT).getHits().getHits();
		List<TbSensitivity> list = new ArrayList<>();
		for (SearchHit hit : hits) {
			TbSensitivity parseObject = JSON.parseObject(hit.getSourceAsString(), TbSensitivity.class);
			list.add(parseObject);
		}

//        List<TbSensitivity> list = articleService.getTbSensitivityList();

        patternBuffer.append("(");
        Iterator<TbSensitivity> iterator = list.iterator();
        while( iterator.hasNext() ){
            String scontent = iterator.next().getSensitivityContent();
            patternBuffer.append(scontent + "|");
            keywordsCount ++;
        }

        patternBuffer.deleteCharAt(patternBuffer.length() - 1);
        patternBuffer.append(")");
        pattern = Pattern.compile(patternBuffer.toString());
        boolean checkMsg = true ;

        Matcher m = pattern.matcher(str);
        while (m.find()) {// 查找符合pattern的字符串
//			System.out.println("The result is here :" + m.group());
            if ( m.group() != null ){
                checkMsg = false ;
            }
        }
        // 选择替换方式，这里以* 号代替
//		str = m.replaceAll("*");
        return checkMsg;
    }


}
